package cn.jaye.fabric.application;

import cn.jaye.fabric.application.command.channel.ListChannelNamesByPeerCommand;
import cn.jaye.fabric.common.constants.exception.UserExceptionEnum;
import cn.jaye.fabric.common.model.ServiceException;
import cn.jaye.fabric.common.model.SystemSession;
import cn.jaye.fabric.domain.model.MPeer;
import cn.jaye.fabric.domain.model.User;
import cn.jaye.fabric.domain.service.OrgService;
import cn.jaye.fabric.domain.service.PeerService;
import cn.jaye.fabric.domain.service.UserService;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Jaye
 * @create 2018-05-18 17:05
 */
@Service
public class ChannelApplicationService {

    @Autowired
    private HFClient hfClient;

    @Autowired
    private UserService userService;

    @Autowired
    private PeerService peerService;

    @Autowired
    private OrgService orgService;

    public Set<String> listChannelNames(ListChannelNamesByPeerCommand listChannelNamesByPeerCommand) throws Exception {
        User user = SystemSession.getUser();
        checkUser(user);
        return hfClient.queryChannels(peerService.getPeer(listChannelNamesByPeerCommand.getPeerId()));
    }

    public Set<String> listAllChannelNames() throws Exception {
        User user = SystemSession.getUser();
        checkUser(user);
        Set<String> result = new HashSet<>();
        Set<Peer> peers = peerService.getPeers(orgService.getOrg(user.getOrgId()));
        for (Peer peer : peers) {
            Set<String> channels = hfClient.queryChannels(peer);
            result.addAll(channels);
        }
        return result;
    }

    private void checkUser(User user) {
        try {
            hfClient.setUserContext(userService.getUser(user));
        } catch (InvalidArgumentException e) {
            e.printStackTrace();
            throw new ServiceException(UserExceptionEnum.USER_ERROR);
        }
    }
}
